﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;
using System.Diagnostics;

namespace template_dll
{
    public partial class ChildForm : Form
    {
        public ChildForm()
        {
            InitializeComponent();
        }

        private const string namechcol = "Флаг";
        private SqlConnection conn;
        private DataTable dt_rep = new DataTable();
        private delegate void Deleg();
        private Deleg del;
        private delegate void DelegChecks();
        private DelegChecks delChecks;


        private struct combox { public int ind; public object val; }
        private combox cb1;
        private combox cb2;
        private SqlStorProc.sp_params[] param = new SqlStorProc.sp_params[2];
        
        public static bool DisplayForm(System.Windows.Forms.Form theMDIParent)
        {
            ChildForm f = new ChildForm();
            f.MdiParent = theMDIParent;
            f.WindowState = FormWindowState.Maximized;
            f.Show();
            return true;
        }

        private string GetServ(string filename)
        {
            string str = "";
            using (StreamReader streamReader = new StreamReader(filename))
            {
                while (!streamReader.EndOfStream)
                {
                    str += streamReader.ReadLine();
                }
            }
            return str;
        }

        private void ChildForm_Load(object sender, EventArgs e)
        {
            conn = new SqlConnection(@"Server=" + GetServ("serv.txt") + ";Database=PharmOLAPDW;Integrated Security=True");
            dateTimePicker2.Value = DateTime.Now.AddDays(-1);
            dateTimePicker1.Value = Convert.ToDateTime(DateTime.Now.AddDays(-1).ToString("yyyy.MM.dd").Substring(0, 8) + "01");
            
            SqlStorProc.sp_params[] bp = new SqlStorProc.sp_params[0];
            DataTable baseMA = (new SqlStorProc()).SqlProcExecWithQueryOneTable(conn, "pas_BaseMASel", 30, bp);
            NewItem ni = new NewItem() { ParamComment = "Все базы", ParamID = null };
            comboBox1.Items.Add(ni);
            comboBox2.Items.Add(ni);
            comboBox1.SelectedIndex = 0;
            comboBox2.SelectedIndex = 0;
            if(baseMA.Rows.Count > 0)
                foreach (DataRow row in baseMA.Rows)
                {
                    NewItem ni1 = new NewItem();
                    ni1.ParamID = row[0];
                    ni1.ParamComment = row[1].ToString();
                    comboBox1.Items.Add(ni1);
                    comboBox2.Items.Add(ni1);
                }
        }

        private void StartCreateRep(object sender, EventArgs e)
        {
            dataGridView1.DataSource = null;
            dt_rep.Clear();
            param[0].name = "@date1";
            param[0].value = dateTimePicker1.Value.ToString("yyyyMMdd");
            param[1].name = "@date2";
            param[1].value = dateTimePicker2.Value.ToString("yyyyMMdd");
            progressBar1.Value = progressBar1.Minimum;
            progressBar2.Value = progressBar2.Minimum;
            del = new Deleg(CreateRep);
            this.Text += " Формируется";
            IAsyncResult asyncRes = del.BeginInvoke(new AsyncCallback(CallBackFunc), null); //
            panel1.Enabled = false;
            dataGridView1.Enabled = false;
        }

        private void CallBackFunc(IAsyncResult aRes)
        {
            del.EndInvoke(aRes);
            panel1.Invoke((Func<bool>)(() => panel1.Enabled = true));
            dataGridView1.Invoke((Func<bool>)(() => dataGridView1.Enabled = true));
            this.Invoke((Func<string>)(() => this.Text = this.Text.Replace(" Формируется", "")));
            dataGridView1.Invoke((Func<object>)(() => dataGridView1.DataSource = dt_rep.DefaultView));
            checkBox1.Invoke((Func<bool>)(() => checkBox1.Checked = true));
        }

        private void CreateRep()
        {
            if (conn.State == ConnectionState.Closed) conn.Open();
            try
            {

                dt_rep = (new SqlStorProc()).SqlProcExecWithQueryOneTable(conn, "pas_DocsMonitor", 120, param);
                dt_rep.Columns.Add("Флаг", Type.GetType("System.Boolean"));
                dt_rep.Columns["Флаг"].SetOrdinal(0);
                foreach (DataColumn dc in dt_rep.Columns)
                    if (dc.Ordinal > 0) dc.ReadOnly = true;


                conn.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                conn.Close();
            }

        }


        private void ExpToExcel(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.FileName = "csv-file";
            sfd.Filter = "Файл CSV | *.csv";
            if (sfd.ShowDialog() == DialogResult.OK)
            {   
                SaveDGVToCSVfile(sfd.FileName.ToString(), dataGridView1, true);
            }
        }

        public static bool SaveDGVToCSVfile(string filename, DataGridView table, bool openInExcel)
        {
            try
            {
                StreamWriter sw = new StreamWriter(filename, false, Encoding.Unicode);

                List<int> col_n = new List<int>();
                foreach (DataGridViewColumn col in table.Columns)
                    if (col.Visible)
                    {
                        sw.Write(col.HeaderText + "\t");
                        col_n.Add(col.Index);
                    }
                sw.WriteLine();
                int x = table.RowCount;
                if (table.AllowUserToAddRows) x--;

                for (int i = 0; i < x; i++)
                {
                    for (int y = 0; y < col_n.Count; y++)
                        sw.Write(table[col_n[y], i].Value + "\t");
                    sw.Write(" \r\n");
                }
                sw.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return false;
            }

            if (openInExcel)
            {
                try
                {
                    Process newProc = Process.Start("excel.exe", "\"" + filename + "\"");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }
            }
            return true;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (dt_rep.Columns.Count > 0)
            {
                //cb2.ind = comboBox2.SelectedIndex;
                //cb2.val = (comboBox2.Items[cb2.ind] as NewItem).ParamID;
                del = new Deleg(DowloadDocs);
                IAsyncResult asyncRes = del.BeginInvoke(new AsyncCallback(DowloadDocs_CallBackFunc), null); //
                button2.Enabled = false;
                button1.Enabled = false;
                comboBox2.Enabled = false;
            }
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if(dt_rep.Rows.Count > 0)
            {
                bool ch = (sender as CheckBox).Checked;
                foreach (DataRow row in dt_rep.Rows) row["Флаг"] = ch;
            }
        }

        private void DowloadDocs_CallBackFunc(IAsyncResult aRes)
        {
            del.EndInvoke(aRes);
            button1.Invoke((Func<bool>)(() => button1.Enabled = true));
            button2.Invoke((Func<bool>)(() => button2.Enabled = true));
            comboBox2.Invoke((Func<bool>)(() => comboBox2.Enabled = true));
        }

        private void DowloadDocs()
        {
            SqlConnection sqlc = new SqlConnection(conn.ConnectionString);
            try
            {
                if (dt_rep.Columns.Count > 0)
                {

                    DataTable fordownload = new DataTable();
                    try
                    {
                        int ind = 0;
                        comboBox2.Invoke((Func<int>)(() => ind = comboBox2.SelectedIndex));
                        object val = null;
                        comboBox2.Invoke((Func<object>)(() => val = (comboBox2.Items[ind] as NewItem).ParamID));
                        if(ind == 0)
                            fordownload = dt_rep.Select("Флаг = 1").CopyToDataTable<DataRow>().DefaultView.ToTable(true, "Код аптеки", "Дата", "ИД базы");
                        else
                            fordownload = dt_rep.Select("Флаг = 1 and [ИД базы] = " + val.ToString()).CopyToDataTable<DataRow>().DefaultView.ToTable(true, "Код аптеки", "Дата", "ИД базы");
                    }
                    catch (Exception ex)
                    {
                        if (ex.Data.Count != 0)
                            throw new Exception();
                    }
                    if (fordownload.Rows.Count > 0)
                    {
                        DataTable fordownload_supp = fordownload.DefaultView.ToTable(true, "Дата", "ИД базы");

                        SqlStorProc.sp_params[] par = new SqlStorProc.sp_params[6];
                        par[0].name = "@datebeg";
                        par[1].name = "@dateend";
                        par[2].name = "@baseid";
                        par[3].name = "@typedoc";
                        par[4].name = "@ph";
                        par[5].name = "@daterec";

                        if (fordownload_supp.Rows.Count > 0)
                        {
                            progressBar1.Invoke((Func<int>)(() => progressBar1.Maximum = fordownload_supp.Rows.Count));
                            progressBar1.Invoke((Func<int>)(() => progressBar1.Value = progressBar1.Minimum));
                            foreach (DataRow dr in fordownload_supp.Rows)
                            {
                                object bid = dr["ИД базы"];
                                object date = dr["Дата"];
                                string pharm = "";
                                foreach (DataRow row in fordownload.Select("[ИД базы] = " + bid.ToString() + " and Дата = '" + date.ToString() + "'").CopyToDataTable<DataRow>().Rows)
                                {
                                    pharm += row["Код аптеки"].ToString() + ",";
                                }

                                par[0].value = date;
                                par[1].value = date;
                                par[2].value = bid;
                                par[3].value = null;
                                par[4].value = pharm.TrimEnd(',');
                                par[5].value = 1;
                                (new SqlStorProc()).SqlProcExecNonQuery(sqlc, "FillDirFactDocData", 600, par);
                                progressBar1.Invoke((Func<int>)(() => progressBar1.Value++));
                            }
                            MessageBox.Show("Все документы загружены");
                        }
                    }
                    else MessageBox.Show("Не выбрана ни одна запись");
                }
                else MessageBox.Show("Нет данных");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                sqlc.Close();
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (dt_rep.Columns.Count > 0)
            {
                cb1.ind = comboBox1.SelectedIndex;
                cb1.val = (comboBox1.Items[cb1.ind] as NewItem).ParamID;
                delChecks = new DelegChecks(DowloadChecks);
                IAsyncResult asyncRes = delChecks.BeginInvoke(new AsyncCallback(DowloadChecks_CallBackFunc), null); //
                button3.Enabled = false;
                button1.Enabled = false;
                comboBox1.Enabled = false;
            }
        }


        private void DowloadChecks_CallBackFunc(IAsyncResult aRes)
        {
            delChecks.EndInvoke(aRes);
            button1.Invoke((Func<bool>)(() => button1.Enabled = true));
            button3.Invoke((Func<bool>)(() => button3.Enabled = true));
            comboBox1.Invoke((Func<bool>)(() => comboBox1.Enabled = true));
        }

        private void DowloadChecks()
        {
            SqlConnection sqlc = new SqlConnection(conn.ConnectionString);
            try
            {
                if (comboBox1.Items.Count > 0)
                {
                    SqlStorProc.sp_params[] par = new SqlStorProc.sp_params[1];
                    par[0].name = "@baseid";

                    DataTable fordownload_supp = new DataTable();
                    fordownload_supp.Columns.Add("ИД базы");

                    int ind = 0;
                    comboBox1.Invoke((Func<int>)(() => ind = comboBox1.SelectedIndex));
                    object val = null;
                    comboBox1.Invoke((Func<object>)(() => val = (comboBox1.Items[ind] as NewItem).ParamID));

                    if (ind == 0)
                    {
                        for (int i = 1; i < comboBox1.Items.Count; i++)
                        {
                            object ob = null;
                            comboBox1.Invoke((Func<object>)(() => ob = (comboBox1.Items[i] as NewItem).ParamID));
                            fordownload_supp.Rows.Add(ob);
                        }
                    }
                    else fordownload_supp.Rows.Add(val);

                    //try
                    //{
                    //    fordownload_supp = dt_rep.Select("Флаг = 1").CopyToDataTable<DataRow>().DefaultView.ToTable(true, "ИД базы");
                    //}
                    //catch (Exception ex)
                    //{
                    //    if (ex.Data.Count != 0)
                    //        throw new Exception();
                    //}

                    if (fordownload_supp.Rows.Count > 0)
                    {
                        progressBar2.Invoke((Func<int>)(() => progressBar2.Maximum = fordownload_supp.Rows.Count));
                        progressBar2.Invoke((Func<int>)(() => progressBar2.Value = progressBar2.Minimum));
                        foreach (DataRow dr in fordownload_supp.Rows)
                        {
                            object bid = dr["ИД базы"];
                            par[0].value = bid;

                            (new SqlStorProc()).SqlProcExecNonQuery(sqlc, "FillDirDocDataReal", 1200, par);
                            progressBar2.Invoke((Func<int>)(() => progressBar2.Value++));
                        }
                        MessageBox.Show("Все чеки загружены");
                    }
                    else MessageBox.Show("Не выбрана ни одна запись");
                }
                else MessageBox.Show("Нет данных");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                sqlc.Close();
            }
        }

        private void progressBar1_Click(object sender, EventArgs e)
        {

        }
    }
}
